package cn.lee.share.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


import cn.lee.TomcatConstants;

public class StaticResourceProcesser {
    public static final int BUFFER_SIZE = 2048;
    private String folder;
    
    
    public void process(Request request, Response response) throws IOException{
        String uri = request.getUri();
        File file = new File( this.getFolder(), uri);
        if(!file.exists()){
            file = new File(TomcatConstants.WEB_ROOT, TomcatConstants.URL_404);
        }
        String cpath = file.getCanonicalPath();
        String postfix = cpath.substring(cpath.lastIndexOf(TomcatConstants.URI_DOT)+1);
        if("html".equals(postfix)){
            response.setContentType("text/html;charset=utf-8");;
        }
        List normalContentType = new ArrayList();
        normalContentType.add("html");
        normalContentType.add("jpg");
        if(!normalContentType.contains(postfix)){
            response.setHeader(response.contentDisposition,"attachment");
        }
        InputStream is = null;
        try{
            is = new FileInputStream(file);
            byte[] b = new byte[BUFFER_SIZE];
            int rsize = 0;
            while((rsize = is.read(b)) != -1){
                response.getOutput().write(b, 0, rsize);
            }
        }finally{
            is.close();
        }
    }


    public String getFolder() {
        if(folder != null && folder != ""){
            return TomcatConstants.WEB_ROOT;
        }
        return folder;
    }


    public void setFolder(String folder) {
        this.folder = folder;
    }
    
    
}
